#!/usr/bin/env bash
# Summary: List hook scripts for a given rbenv command
# Usage: rbenv hooks <command>

set -e
[ -n "$RBENV_DEBUG" ] && set -x

# Provide rbenv completions
if [ "$1" = "--complete" ]; then
  echo exec
  echo rehash
  echo version-name
  echo version-origin
  echo which
  exit
fi

RBENV_COMMAND="$1"
if [ -z "$RBENV_COMMAND" ]; then
  rbenv-help --usage hooks >&2
  exit 1
fi

if ! enable -f "${BASH_SOURCE%/*}"/rbenv-realpath.dylib realpath 2>/dev/null; then
  if [ -n "$RBENV_NATIVE_EXT" ]; then
    echo "rbenv: failed to load \`realpath' builtin" >&2
    exit 1
  fi
READLINK=$(type -p greadlink readlink 2>/dev/null | head -1)
if [ -z "$READLINK" ]; then
  echo "rbenv: cannot find readlink - are you missing GNU coreutils?" >&2
  exit 1
fi

resolve_link() {
  $READLINK "$1"
}

realpath() {
  local cwd="$PWD"
  local path="$1"
  local name

  while [ -n "$path" ]; do
    name="${path##*/}"
    [ "$name" = "$path" ] || cd "${path%/*}"
    path="$(resolve_link "$name" || true)"
  done

  echo "${PWD}/$name"
  cd "$cwd"
}
fi

IFS=: hook_paths=($RBENV_HOOK_PATH)

shopt -s nullglob
for path in "${hook_paths[@]}"; do
  for script in "$path/$RBENV_COMMAND"/*.bash; do
    realpath "$script"
  done
done
shopt -u nullglob
